<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>管理页面</title>
    <script src="/pub/js/ly.import.js"></script>
</head>
<body>
<div id="app">
    <el-container>
        <el-header style="height: auto">
            <el-form :inline="true">
                <el-form-item v-for="c in wheres" :label="c.comment.split(/[^\w\u4E00-\u9FA5]+/)[0]">
                    <el-input v-model="where[c.name]"
                              :title="c.type+' '+c.comment.replace(/[\w\u4E00-\u9FA5]+([^\w\u4E00-\u9FA5]+(.+))?/,'$2')"
                              :placeholder="c.type+' '+c.comment.replace(/[\w\u4E00-\u9FA5]+([^\w\u4E00-\u9FA5]+(.+))?/,'$2')"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="query(1)" type="primary" size="mini" plain>查询</el-button>
                    <el-button @click="mod({})" type="primary" size="mini" plain>添加</el-button>
                    <el-button @click="open(table.name+'/down','_blank')" type="primary" size="mini" plain>下载</el-button>
                    <el-button @click="backup(table.name)" type="primary" v-if="I.role==0" size="mini" plain>备份</el-button>
                    <el-button @click="restore(table.name)" type="primary" v-if="I.role==0" size="mini"plain>恢复</el-button>
                </el-form-item>
            </el-form>
        </el-header>
        <el-main style="overflow: hidden">
            <el-table :max-height="tableMaxHeight" :data="page.rows" :row-style="rowstyle" border style="width: 100%;">
                <el-table-column type="index" label="序号" width="50"></el-table-column>
                <el-table-column v-for="c in columns" :prop="c.name"
                                 :label="c.comment.split(/[^\w\u4E00-\u9FA5]+/)[0]"
                                 :width="getWidth(c)">
                    <template v-slot="scope">
                        {{getText(c, scope.row[c.name])}}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="160" :fixed="flag.opfix" align="center">
                    <template v-slot="scope">
                        <el-link style="margin-right: 5px;color:rgba(96, 98, 102, 0.6)" @click="mod(scope.row)" :underline="false">修改</el-link>
                        <el-link style="margin-right: 5px;color:rgba(96, 98, 102, 0.6)" @click="del(scope.row)" :underline="false">删除</el-link>
                    </template>
                </el-table-column>
            </el-table>
            <div style="text-align: right; padding: 10px 0px">
                <el-pagination @current-change="query" background @size-change="query(1)"
                               layout="sizes, total, prev, pager, next" :total="page.total"
                               :page-size.sync="page.size"/>
            </div>
        </el-main>
    </el-container>
    <el-dialog title="编辑窗口" :visible.sync="flag.showDlg">
        <el-container>
            <el-main>
                <el-form ref="form" :model="form" label-width="80px">
                    <el-form-item v-for="c in columns" :label="c.comment.split(/[^\u4E00-\u9FA5]+/)[0]">
                        <el-date-picker v-if="c.type=='date'||c.type=='timestamp'" v-model="form[c.name]" type="date"
                                        :placeholder="c.type+' '+c.comment.replace(/[\u4E00-\u9FA5]+([^\u4E00-\u9FA5]+(.+))?/,'$2')">
                        </el-date-picker>
                        <el-input v-else v-model="form[c.name]" :disabled="c.key=='PRI'"
                                  :placeholder="c.type+' '+c.comment.replace(/[\u4E00-\u9FA5]+([^\u4E00-\u9FA5]+(.+))?/,'$2')"></el-input>
                    </el-form-item>
                </el-form>
            </el-main>
            <el-footer style="text-align: center;">
                <el-button type="primary" @click="save">保存</el-button>
                <el-button @click="flag.showDlg=false">取消</el-button>
            </el-footer>
        </el-container>
    </el-dialog>
</div>
<script>
    var v = new Vue({
        el: "#app",
        data: {I: {},
            table: {}, columns: [],
            page: {page: 1, size: 10},
            form: {}, where: {},
            flag: {showDlg: false, opfix: false},
            tableMaxHeight: 500
        },
        created() {
            this.table.name = location.search.substring(1);
            if(this.table.name=='demo_table')return;
            this.table.comment = decodeURI(location.hash.substring(1));
            this.table.maxid = this.table.comment.replace(/(.+)(-(\d+))+/, "$3");
            this.table.maxid = parseInt(this.table.maxid);
            this.table.comment = this.table.comment.replace(/(.+?)(-\d+)+/, "$1");
            axios.get("/login/myinfo").then(res => this.I = res.data);
            this.queryColumns();
            this.query();
        },
        mounted() {
            document.querySelector(".el-dialog").style.marginTop = '5vh';
            this.resetTableMaxheight();
        },
        computed: {
            wheres() {
                if (this.columns.length <= 3) {
                    return this.columns
                } else {
                    let ret = [];
                    this.columns.forEach(c => {
                        if (ret.length < 3 && c.type.indexOf('varchar') == 0) {
                            ret.push(c);
                        }
                    });
                    this.columns.forEach(c => {
                        if (ret.length < 3 && !ret.find(c1 => c1.name == c.name)) {
                            ret.push(c);
                        }
                    });
                    ret.sort((c1, c2) => this.columns.findIndex(
                        c => c.name == c1.name) - this.columns.findIndex(c => c.name == c2.name));
                    return ret;
                }
            }
        },
        methods: {
            resetTableWidth(){
                var table = document.querySelector("div.el-table__body-wrapper");
                if (table.offsetWidth < table.scrollWidth) {
                    this.flag.opfix = 'right';
                } else {
                    this.flag.opfix = false;
                }
            },
            rowstyle(data, index) {
                return {
                    backgroundColor: !this.table.maxid || data.row.id > this.table.maxid ? '' : '#fcf6f5',
                    color: !this.table.maxid || data.row.id > this.table.maxid ? 'rgb(96, 98, 102)' : 'rgba(96, 98, 102, 0.5)',
                    cursor: 'pointer'
                };
            },
            query(page) {
                if (page) {
                    this.page.page = page;
                }
                let p = new URLSearchParams();
                p.append("page", this.page.page);
                p.append("size", this.page.size);
                this.wheres.forEach(c => {
                    let value = this.where[c.name];
                    if (value) {
                        if (c.type.indexOf('varchar') == 0 || c.type.indexOf('text') == 0) {
                            p.append(c.name, "%" + value + "%");
                        } else if (c.type.indexOf('date') == 0 || c.type.indexOf('timpstamp') == 0) {
                            p.append(c.name, parseDate(value).format('yyyy-MM-dd'));
                        } else {
                            p.append(c.name, value);
                        }
                    }
                })
                axios.post(`${this.table.name}/page`, p).then(res => {
                    this.page.rows = res.data.rows;
                    this.page.total = res.data.total;
                    this.$forceUpdate();
                    this.$nextTick(()=>{
                        this.resetTableMaxheight();
                    })
                });
            },
            queryColumns() {
                axios.get("/easy/columns?table=" + this.table.name).then(res => {
                    this.columns = res.data;
                    this.columns.forEach(c => {
                        if (c.key == "PRI") {
                            this.table.key = c.name;
                        }
                    });
                    this.$forceUpdate();
                    setTimeout(()=>{
                        this.resetTableWidth();
                    },100);
                });
            },
            getWidth(column) {
                if (column.type.indexOf('int') == 0) {
                    return 80;
                } else {
                    return 180;
                }
            },
            getText(column, value) {
                if (value && (column.type.indexOf('varchar') == 0 || column.type.indexOf('text') == 0)) {
                    let ret = value.substring(0, 20);
                    return value.length > 20 ? ret + '...' : ret;
                } else if (value && column.type.indexOf('date') == 0) {
                    return parseDate(value).format("yyyy年MM月dd日");
                } else if (value && column.type.indexOf('timestamp') == 0) {
                    return parseDate(value).format("yyyy年MM月dd日 hh时mm分ss秒");
                } else {
                    return value;
                }
            },
            del(row) {
                this.$confirm("请确认是否要删除该记录?", "系统提示").then(() => {
                    axios.get(`${this.table.name}/remove?${this.table.key}=` + row[this.table.key]).then(res => {
                        if (res.data.code) {
                            this.$message(res.data.msg);
                            this.query();
                        } else {
                            this.$alert(res.data.msg);
                        }
                    })
                });
            },
            mod(row) {
                this.openEdit(row);
            },
            openEdit(row) {
                let form = {};
                for (let name in row) {
                    form[name] = row[name];
                }
                this.form = form;
                this.flag.showDlg = true;
            },
            save() {
                let p = new URLSearchParams();
                for (let name in this.form) {
                    if (this.form[name]) {
                        let value = this.form[name];
                        let type = this.columns.find(c => c.name == name).type;
                        if (type.indexOf('date') == 0) {
                            value = parseDate(value).format("yyyy-MM-dd");
                        } else if (type.indexOf('timestamp') == 0) {
                            value = parseDate(value).format("yyyy-MM-dd hh:mm:ss");
                        }
                        p.append(name, value);
                    }
                }
                axios.post(this.table.name + "/save", p).then(res => {
                    if (res.data.code) {
                        this.$message(res.data.msg);
                        this.query();
                        this.flag.showDlg = false;
                    } else {
                        this.$alert(
                            `<h4>${res.data.msg}</h4>
                             <p>原因：</p>
                             <p>${res.data.data}</p>`,
                            {dangerouslyUseHTMLString:true});
                    }
                })
            },
            backup(table) {
                axios.get(table + "/backup").then(res => {
                    if (res.data.code) {
                        this.$message(res.data.msg);
                    } else {
                        this.$alert(res.data.msg);
                    }
                });
            },
            restore(table) {
                axios.get(table + "/restore").then(res => {
                    if (res.data.code) {
                        this.$message(res.data.msg);
                    } else {
                        this.$alert(res.data.msg);
                    }
                });
            },
            resetTableMaxheight(){
                setTimeout(()=>{
                    let elmain = document.querySelector(".el-main");
                    this.tableMaxHeight = elmain.offsetHeight - 70;
                },100)
            }
        }
    })
</script>
</body>
</html>

<style>
    html, body, #app, .el-container {
        margin: 0px;
        padding: 0px;
        height: 100%;
        overflow-y: hidden;
    }

    .el-dialog {
        height: calc(100% - 10vh);
    }

    .el-dialog__body {
        height: calc(100% - 54px);
        box-sizing: border-box;
    }

    .el-footer {
        padding: 20px 0px;
    }

    .el-form-item {
        margin-bottom: 0px;
    }

    .el-input__inner {
        height: 30px;
    }

    .el-main{
        padding: 10px 0px 0px;
    }

    .el-table__row>.el-table__cell{
        padding: 1px;
    }
</style>